package org.exteen.exec;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.exteen.ExteenException;
import org.exteen.lib.LibraryMap;
import org.exteen.lib.TagLibrary;
import org.exteen.parser.Node;

public class TopContext extends ExteenContext {

    private ArrayList<ExteenContext> cache = new ArrayList<ExteenContext>();
    private LibraryMap libraryMap = new LibraryMap();

    public TopContext(Map<String, Object> map, List<? extends TagLibrary> bootLibraries) {
        this.variables = new HashMap<String, Object>();
        this.variables.putAll(map);
        this.libraryMap.addAll(bootLibraries);
    }

    protected ExteenContext createChildContext(ExteenContext parent, Node node) {
        if (cache.size()==0) {
            return new ExteenContext(parent, node);
        } else {
            ExteenContext fromCache = cache.remove(cache.size() - 1);
            fromCache.init(parent, node);
            return fromCache;
        }
    }

    public final void addLibrary(TagLibrary library) {
        if (libraryMap.get(library.getId()) != null) {
            throw new ExteenException("Library with ID " + library.getId() + " already defined");
        }
        libraryMap.addLibrary(library);
    }

    protected TagLibrary getLibrary(String id) {
        return libraryMap.get(id);
    }

    protected void putCotextToPool(ExteenContext ctx) {
        cache.add(ctx);
    }
}
